package dhee.wtqshopproject.utils;

import dhee.wtqshopproject.dao.ProductIndexMapper;
import dhee.wtqshopproject.entity.Product;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ProductIndexUtils {

    private static ProductIndexUtils productMapperUtils;

    @Resource
    private ProductIndexMapper productIndexMapper;

    @PostConstruct
    public void init() {
        productMapperUtils = this;
        productMapperUtils.productIndexMapper = this.productIndexMapper;
    }

    // 根据分类ID分页查询前6个展示商品
    public static List<Product> selectByCategoryWithLimit(Integer categoryId, int offset) {
        return productMapperUtils.productIndexMapper.selectByCategoryWithLimit(categoryId, offset);
    }

    // 查询每个分类前6个商品
    public static Map<String, List<Product>> selectByCategoriesWithLimit() {
        List<Product> products = productMapperUtils.productIndexMapper.selectByCategoriesWithLimit();
        return products.stream()
                .collect(Collectors.groupingBy(
                        Product::getCategoryId,
                        Collectors.toList()
                ));
    }

    // 商品搜索（名称或描述模糊查询）
    public static List<Product> searchProducts(String keyword) {
        return productMapperUtils.productIndexMapper.searchProducts(keyword);
    }

    // 商品详情查询
    public static Product selectProductById(Integer productId) {
        return productMapperUtils.productIndexMapper.selectProductById(productId);
    }
}
